from dotenv import load_dotenv
import os

# New environment loading logic
# 读取运行环境
run_env = os.environ.get('APP_ENV', '')
# 运行环境未指定时默认加载.env.dev
env_file = '.env.dev'
# 运行环境不为空时按命令行参数加载对应.env文件
if run_env != '':
    env_file = f'.env.{run_env}'
# 加载配置
load_dotenv(env_file)

from robyn import Robyn
from models.database import create_db
import importlib
import pkgutil
import inspect
import sys

# Import all model files to ensure they are registered with SQLAlchemy's Base.metadata
import models.do.user_do
import models.do.role_do
import models.do.permission_do
import models.do.user_role_do
import models.do.role_permission_do
import models.do.crime_do

create_db()  # This will now create all tables defined in the imported models

app = Robyn(__file__)



@app.get("/")
def index():
    return "Hello World!"


def load_controllers(app):
    """
    使用反射方法从controllers文件夹中动态加载所有控制器
    """
    controllers_package = 'controllers'

    # 获取controllers包的完整路径
    controllers_path = os.path.join(os.path.dirname(__file__), 'controllers')

    # 动态导入controllers包
    if controllers_path not in sys.path:
        sys.path.insert(0, os.path.dirname(__file__))

    try:
        # 使用pkgutil遍历controllers包中的所有模块
        controllers_module = importlib.import_module(controllers_package)

        for importer, modname, ispkg in pkgutil.iter_modules(controllers_module.__path__, controllers_package + "."):
            try:
                # 动态导入模块
                module = importlib.import_module(modname)

                # 使用inspect获取模块中的所有成员
                for name, obj in inspect.getmembers(module):
                    # 检查是否是SubRouter实例（Robyn的路由控制器）
                    if hasattr(obj, '__class__') and obj.__class__.__name__ == 'SubRouter':
                        # 检查对象名称是否以_controller结尾（约定优于配置）
                        if name.endswith('_controller'):
                            print(f"正在加载控制器: {name} 从模块 {modname}")
                            app.include_router(obj)
                            print(f"[SUCCESS] 成功加载控制器: {name}")

            except Exception as e:
                print(f"[WARNING] 警告: 加载模块 {modname} 失败: {str(e)}")
                continue

    except Exception as e:
        print(f"[WARNING] 警告: 加载controllers包失败: {str(e)}")
        # 如果反射加载失败，回退到手动导入
        # print("正在回退到手动导入模式...")
        # from controllers.crimes_controller import crimes_controller
        # from controllers.auth_controller import auth_controller
        # app.include_router(crimes_controller)
        # app.include_router(auth_controller)


# 使用反射方法加载所有控制器
load_controllers(app)

if __name__ == "__main__":
    app.start(host="0.0.0.0", port=8080)